<template>
  <!-- 修改密码弹窗 -->
  <el-dialog v-model="dialogPassword" title="修改密码" width="40%">
    <el-form
      ref="signFormRef"
      :model="signForm"
      status-icon
      :rules="signRules"
      label-position="right"
      label-width="100px"
      style="max-width: 460px"
      class="login_form"
    >
      <el-form-item label="新密码：" prop="password">
        <el-input type="password" v-model="signForm.password" autocomplete="off" show-password />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input
          v-model="signForm.confirmPassword"
          type="password"
          autocomplete="off"
          show-password
          @blur="handleConfirm"
        ></el-input>
      </el-form-item>
      <el-button type="primary" class="loginBtn" @click="dialogPassword = false"> 取消 </el-button>
      <el-button type="primary" class="loginBtn" @click="onSubmit"> 确定 </el-button>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, toRefs } from 'vue'
import { usePasswordDialog } from '@/stores/dialogPassword.js'
import { ElMessage } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
const { dialogPassword } = toRefs(usePasswordDialog())
const { proxy } = getCurrentInstance()
const $router = useRouter()
const signForm = ref({
  password: '',
  confirmPassword: ''
})
const signFormRef = ref('ruleFormRef')
const signRules = ref({
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 3, max: 7, message: '密码长度为3-7个字符', trigger: 'blur' }
  ]
})
// 确认密码
const handleConfirm = () => {
  if (signForm.value.confirmPassword != signForm.value.password)
    ElMessage.error('密码与确认密码不一致')
}
const username = localStorage.getItem('user_name')
const onSubmit = async () => {
  const res = await proxy.$http.put(`/user/update_user_password/${username}`, {
    user_password: signForm.value.password
  })
  if (res.code == 0) {
    dialogPassword.value = false
    // 1.清除登录状态
    localStorage.clear()
    // 2.路由到登录页面
    $router.push('/login')
    ElMessage({
      message: '修改成功，请重新登录',
      type: 'success',
      duration: 1500
    })
  } else {
    ElMessage({
      message: '修改失败',
      type: 'error',
      duration: 1500
    })
  }
}
</script>

<style scoped>
.identify_code {
  width: 255px;
}
</style>
